package com.jlnk.androidfmc;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jlnk.androidfmc.entity.CartItem;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class OrderDetailsActivity extends AppCompatActivity {


    private List<CartItem> orderItems = new ArrayList<>();
    private OrderAdapter orderAdapter;
    private TextView tvOrderStatus;
    private TextView tvOrderTotalPrice;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_details);
        initViews();
        getOrderDetailsFromIntent();
    }

    private void initViews() {
        RecyclerView rvOrderItems = findViewById(R.id.rv_order_items);
        tvOrderStatus = findViewById(R.id.tv_order_status);
        tvOrderTotalPrice = findViewById(R.id.tv_order_total_price);

        orderAdapter = new OrderAdapter(orderItems);
        rvOrderItems.setLayoutManager(new LinearLayoutManager(this));
        rvOrderItems.setAdapter(orderAdapter);
    }

    private void getOrderDetailsFromIntent() {
        Intent intent = getIntent();
        String orderItemsJson = intent.getStringExtra("ORDER_ITEMS");
        String totalAmountStr = intent.getStringExtra("TOTAL_AMOUNT");

        Log.d("OrderDetailsActivity", "Received order items JSON: " + orderItemsJson);
        Log.d("OrderDetailsActivity", "Received total amount string: " + totalAmountStr);

        if (orderItemsJson == null || totalAmountStr == null) {
            Log.e("OrderDetailsActivity", "Received null data for ORDER_ITEMS or TOTAL_AMOUNT");
            showErrorAndFinish(); // 处理错误情况
        } else {
            try {
                Gson gson = new Gson();
                Type type = new TypeToken<ArrayList<CartItem>>(){}.getType();
                orderItems = gson.fromJson(orderItemsJson, type);
                setTotalAmount(Double.parseDouble(totalAmountStr));
                orderAdapter.setItems(orderItems); // 更新适配器数据
            } catch (NumberFormatException e) {
                Log.e("OrderDetailsActivity", "Error parsing total amount", e);
                showErrorAndFinish();
            }
        }
    }

    private void showErrorAndFinish() {
        Toast.makeText(this, "Error loading order details.", Toast.LENGTH_LONG).show();
        finish();
    }

    private void setTotalAmount(double total) {
        tvOrderTotalPrice.setText(String.format("¥%.2f", total));
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存订单项和总金额
        outState.putString("ORDER_ITEMS_JSON", new Gson().toJson(orderItems));
        outState.putString("TOTAL_AMOUNT_STR", String.valueOf(tvOrderTotalPrice.getText()));
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // 恢复订单项和总金额
        if (savedInstanceState != null) {
            String orderItemsJson = savedInstanceState.getString("ORDER_ITEMS_JSON");
            String totalAmountStr = savedInstanceState.getString("TOTAL_AMOUNT_STR");
            if (orderItemsJson != null && totalAmountStr != null) {
                getOrderDetailsFromIntent(); // 使用保存的数据
            }
        }
    }
    // 订单商品项的简单类
    public static class OrderItem {
        private String name;
        private int quantity;
        private double price;

        public OrderItem(String name, int quantity, double price) {
            this.name = name;
            this.quantity = quantity;
            this.price = price;
        }

        // getters and setters
        public String getName() {
            return name;
        }

        public int getQuantity() {
            return quantity;
        }

        public double getPrice() {
            return price;
        }
    }

    // RecyclerView 的适配器
    public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.OrderViewHolder> {
        private List<CartItem> items = new ArrayList<>();
        // 构造函数
        public OrderAdapter(List<CartItem> items) {
            this.items = items;
        }

        // setItems 方法
        public void setItems(List<CartItem> items) {
            this.items = items;
            notifyDataSetChanged(); // 通知数据集已更改
        }
        @Override
        public OrderViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_order, parent, false);
            return new OrderViewHolder(view);
        }


        @Override
        public void onBindViewHolder(OrderViewHolder holder, int position) {
            CartItem item = items.get(position);
            holder.tvItemName.setText(item.getName());
            holder.tvItemQuantity.setText("x" + item.getQuantity());
            holder.tvItemPrice.setText("¥ " + item.getPrice());
        }

        @Override
        public int getItemCount() {
            return items.size();
        }

        public class OrderViewHolder extends RecyclerView.ViewHolder {
            public TextView tvItemName;
            public TextView tvItemQuantity;
            public TextView tvItemPrice;

            public OrderViewHolder(View itemView) {
                super(itemView);
                tvItemName = itemView.findViewById(R.id.tv_item_name);
                tvItemQuantity = itemView.findViewById(R.id.tv_item_quantity);
                tvItemPrice = itemView.findViewById(R.id.tv_item_price);
            }
        }
    }
}